<template>
  <div style="width: 100%;padding-bottom: 50px">
    <div style="margin: 20px">
      <span style="font-size: 18px;color: black">收货地址</span>
    </div>
    <el-row :gutter="20" style="width: 100%;margin-left: 10px">
      <!-- 地址卡片 -->
      <el-col :span="8" v-for="(address, index) in addresses" :key="index" >
        <el-card class="box-card"  shadow="hover" >
          <div v-for="(item, key) in address" :key="item" class="text item">
            <span v-if="key!=='id'">{{ item }}</span>
          </div>
          <div align="right">
            <div v-if="myAddress">
              <el-button type="text" @click="modifyAddress(index)">修改</el-button>
              <el-button type="text" @click="deleteAddress(index)">删除</el-button>
            </div>
            <div v-else>
              <el-button type="text" @click="choseButton(index,$event)">选择</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="box-card pointer" shadow="hover" >
          <div style="margin-top: 37px" align="center" @click="addAddress">
            <i class="el-icon-circle-plus-outline" style="font-size:30px"></i>
            <br>
            <span>添加新地址</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!--新增/修改的弹窗-->
    <el-dialog :title="form.title" :visible.sync="dialogVisible" width="20%">
      <el-form :model="form" :rules="rules" ref="form" class="demo-form-inline">
        <el-form-item prop="receiver">
          <el-input v-model="form.receiver" placeholder="收货人姓名" clearable  :hide-required-asterisk="false"></el-input>
        </el-form-item>
        <el-form-item prop="telephone">
          <el-input v-model="form.telephone" placeholder="电话号码" clearable></el-input>
        </el-form-item>
        <el-form-item prop="province">
          <el-select v-model="form.province" placeholder="省" style="width: 100%">
            <el-option v-for="(value, name, index) in provinceList" :key="index" :label="value" :value="value" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="city">
          <el-select v-model="form.city" placeholder="市" :disabled="this.form.province===''" style="width: 100%">
            <div v-for="item in cityChoice" :key="item">
              <el-option  :label="item" :value="item" ></el-option>
            </div>
          </el-select>
        </el-form-item>
        <el-form-item >
          <el-select v-model="form.district" placeholder="县/区" :disabled="this.form.city===''" style="width: 100%">
            <div v-for="item in districtChoice" :key="item">
              <el-option  :label="item" :value="item" ></el-option>
            </div>
          </el-select>
        </el-form-item>
        <el-form-item >
          <el-input type="textarea" :rows="2" placeholder="详细地址" v-model="form.detail" maxlength="30"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">提 交</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { addressMap } from '@/assets/addressMap'
import { getAddress, updateAddress, deleteAddrss } from "@/api/user";

export default {
  name: "userAddress",
  data() {
    return {
      // 收货地址的list
      addresses: [
        // {
        //   id: "",
        //   receiver: "力哈哈",
        //   telephone: "13822222222",
        //   address: "江苏省 南通市 崇川区 和平桥街道",
        //   detail: "燕园88号",
        // },
      ],
      dialogVisible: false,
      // 添加收货地址的表单
      form: {
        title: '添加收货地址',
        id: "",
        receiver: '',
        telephone: '',
        province: '',
        city: '',
        district: '',
        detail: ''
      },
      // 表单校验
      rules: {
        receiver: [
          {required: true, trigger: 'blur', message: '*请输入收货人姓名'}
        ],
        telephone: [
          {required: true, trigger: 'blur', message: '*请输入收货人电话'}
        ],
        province: [
          {required: true, trigger: 'blur', message: '*请选择收货地址'}
        ]
      },
      // 省的list
      provinceList: addressMap.province_list,
      // 市的list
      cityList: addressMap.city_list,
      // 区的list
      districtList: addressMap.district_lsit,
      // 被选中的地址的addressId
      ChosenAddressId: undefined
    }
  },
  created() {
    this.getAddresses()
  },
  computed: {
    cityChoice() {
      let code = '';
      let cityes = {};
      for (let item in this.provinceList) {
        if (this.form.province === this.provinceList[item]) {
          code = item.substr(0, 2)
        }
      }
      for (let key in this.cityList) {
        if (key.substr(0, 2) === code) {
          cityes[key] = this.cityList[key]
        }
      }
      return cityes;
    },
    districtChoice() {
      let code = '';
      let districts = {};
      for (let item in this.cityList) {
        if (this.form.city === this.cityList[item]) {
          code = item.substr(0, 4)
        }
      }
      for (let key in this.districtList) {
        if (key.substr(0, 4) === code) {
          districts[key] = this.districtList[key]
        }
      }
      return districts;
    },
    myAddress: function () {
      return location.pathname === "/User_Portal/userAddress";
    }
  },
  methods: {
    //获取收货地址
    getAddresses() {
      getAddress().then( response => {
        let addressList = response.address
        this.addresses = []
        for (let i=0;i<addressList.length;i++) {
          let tmp = {}
          tmp.id = addressList[i].id;
          tmp.receiver = addressList[i].receiver;
          tmp.telephone = addressList[i].telephone;
          tmp.address = addressList[i].province + " " + addressList[i].city + " " + addressList[i].district
          tmp.detail = addressList[i].detail;
          this.addresses.push(tmp)
        }
      })
    },
    // 重置表单
    resetForm(formName) {
      for (let key in formName) {
        formName[key] = ''
      }
    },
    // 新增地址
    addAddress() {
      this.resetForm(this.form)
      this.form.title = '添加收货地址'
      this.dialogVisible = true;
    },
    // 修改地址
    modifyAddress(index) {
      this.resetForm(this.form)
      this.form.title = '修改收货地址'
      this.dialogVisible = true;
      this.form.id = this.addresses[index].id;
      this.form.receiver = this.addresses[index].receiver;
      this.form.telephone = this.addresses[index].telephone;
      this.form.province = this.addresses[index].address.split(' ')[0]
      this.form.city = this.addresses[index].address.split(' ')[1]
      this.form.district = this.addresses[index].address.split(' ')[2]
      this.form.detail = this.addresses[index].detail
    },
    //删除地址
    deleteAddress(index) {
      this.$confirm('是否确认删除该地址吗？：', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteAddrss(this.addresses[index].id).then((response) => {
          alert(response.message)
          this.getAddresses()
        })
      })
    },
    //提交新增/修改地址的form
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          updateAddress(this.form).then((response) => {
            alert(response.message)
            this.dialogVisible = false;
            this.getAddresses()
          })
        } else {
          // console.log('error submit!!');
          return false;
        }
      })
    },
    // 选择按钮的功能
    choseButton(index,event) {
      let clsObjs = document.getElementsByClassName("box-card");
      for (let i = 0; i < clsObjs.length; i++) {
        clsObjs[i].style.borderColor = "#e0e0e0";
      }
      let el = event.currentTarget.parentNode.parentNode.parentNode.parentNode;
      el.style.borderColor = 'red'
      this.ChosenAddressId = this.addresses[index].id;
    },
  },
}
</script>

<style scoped>

span {
  font-size: 15px;
}

.box-card {
  height: 166px;
  border-color: #e0e0e0;
  margin-bottom: 20px;
}

.pointer {
  cursor: pointer;
}

/deep/ .el-dialog__footer {
  text-align: center;
}
</style>
